﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ChurchEdu.Models;
using System.Web.Security;
using WebMatrix.WebData;
using ChurchEdu.Lib;
using DataModel;
using System.IO;
using System.Data.Entity;
using System.Data;
using Webdiyer.WebControls.Mvc;
namespace ChurchEdu.Controllers
{
      [Authorize]
    public class ResourceController : Controller
    {
        //
        // GET: /Resource/
          private Church_DataEntities db;
        private IResource ibl;
        protected List<int> resourcecategoryid = new List<int>();

        public  ResourceController()
        {
            db = new Church_DataEntities();
           ibl = new ResourceBL(this.ModelState);
        
        }

            [Authorize(Roles = "Admin")] 
        public ActionResult CheckIndex()
        {
            var aa = from a in db.Resource where a.ResCheck==0
                     join b in db.UserProfile on a.UserID equals b.UserId
                     select new RescourcerList
                     {
                         rescourceid = a.ID,
                         DateTimeStamp = a.DateTimeStamp,
                         Descrb = a.Descrb,
                         LatestModfyDate = a.LatestModfyDate,
                         Location = a.Location,
                         PlayTime = a.PlayTime,
                         PraiseTime = a.PlayTime,
                         Title = a.Title,
                         username = b.UserName, 
                         ImageshotFileName = a.ImageshotFileName

                     };
            return View(aa);
        }

        //public ActionResult main(int resourceid)
        //{
        //    var aa = from a in db.Resource
        //             where a.ResCheck == 0
        //             join b in db.UserProfile on a.UserID equals b.UserId
        //             select new RescourcerList
        //             {
        //                 rescourceid = a.ID,
        //                 DateTimeStamp = a.DateTimeStamp,
        //                 Descrb = a.Descrb,
        //                 LatestModfyDate = a.LatestModfyDate,
        //                 Location = a.Location,
        //                 PlayTime = a.PlayTime,
        //                 PraiseTime = a.PlayTime,
        //                 Title = a.Title,
        //                 username = b.UserName,
        //                 ImageshotFileName = a.ImageshotFileName

        //             };
        //    return View(aa);
        //}



        public void UnZip(string zipedFile, string strDirectory,  bool overWrite)
        {
            if (strDirectory == "")

                strDirectory = Directory.GetCurrentDirectory();

            if (!strDirectory.EndsWith("\\"))

                strDirectory = strDirectory + "\\";
            using (ZipInputStream s = new ZipInputStream(System.IO.File.OpenRead(zipedFile)))
            {
                
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directoryName = "";
                    string pathToZip = "";
                    pathToZip = theEntry.Name;
                    if (pathToZip != "")
                        directoryName = Path.GetDirectoryName(pathToZip) + "\\";
                    string fileName = Path.GetFileName(pathToZip);
                    Directory.CreateDirectory(strDirectory + directoryName);
                    if (fileName != "")
                    {
                        if ((System.IO.File.Exists(strDirectory + directoryName + fileName) && overWrite) || (!System.IO.File.Exists(strDirectory + directoryName + fileName)))
                        {
                            using (FileStream streamWriter = System.IO.File.Create(strDirectory + directoryName + fileName))
                            {
                                int size = 2048;
                                byte[] data = new byte[2048];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                        streamWriter.Write(data, 0, size);
                                    else
                                        break;
                                }
                                streamWriter.Close();
                            }
                       }

                    }

                }
                s.Close();
            }
        }

        [Authorize(Roles = "Admin")] 
        public static void DeleteFolder(string dir)
        {
            if (Directory.Exists(dir)) //如果存在这个文件夹删除之      
            {
                foreach (string d in Directory.GetFileSystemEntries(dir))
                {
                    if (System.IO.File.Exists(d)) System.IO.File.Delete(d);
                    else DeleteFolder(d);
                }
                Directory.Delete(dir, true);
            }
        }





        public static void DeleteDir(string aimPath)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加之
                if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                    aimPath += Path.DirectorySeparatorChar;
                // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
                // 如果你指向Delete目标文件下面的文件而不包含目录请使用下面的方法
                // string[] fileList = Directory.GetFiles(aimPath);
                string[] fileList = Directory.GetFileSystemEntries(aimPath);
                // 遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    // 先当作目录处理如果存在这个目录就递归Delete该目录下面的文件
                    if (Directory.Exists(file))
                    {
                        DeleteDir(aimPath + Path.GetFileName(file));
                    }
                    // 否则直接Delete文件
                    else
                    {
                        System.IO.File.Delete(aimPath + Path.GetFileName(file));
                    }
                }
                //删除文件夹
                System.IO.Directory.Delete(aimPath, true);
            }
            catch
            {

            }
        }



        [AllowAnonymous]
        public ActionResult checkVr (int rescourceid)
        {
            
            var aa = (from a in db.Resource
                     where a.ID == rescourceid
                     select new checkvr
                         {
                             Location = a.Location,
                             Descrb = a.Descrb,
                             Title=a.Title,
                              subtitle=a.SubTitle,
                             PlayTime =  a.PlayTime,
                             PraiseTime =a.PraiseTime,
                             resourceid = rescourceid,
                              resourceurl=a.PackageFileName,
                                imageurl=a.ImageshotFileName
                         }).SingleOrDefault();

            ViewData["resourcegategoryid"] = db.ResourceCategory.FirstOrDefault(a => a.ResourceID == rescourceid);
            ViewData["categoryname"] = (from a in db.Category join b in db.ResourceCategory on a.ID equals b.CategoryID join c in db.Resource on b.ResourceID equals c.ID where c.ID == rescourceid select a);
           // string zipUrl = Server.MapPath("~/Uploads/" + rescourceid + "/" + aa.resourceurl);
          //  string path = Server.MapPath("~/Uploads/" + rescourceid + "/" + rescourceid + "/");
            //if (!Directory.Exists(path))
            //{
            //    try { UnZip(zipUrl, path, true); }
            //    catch
            //    {
            //        var script = String.Format("<script>alert('zip资源包解析错误，请重新上传zip包');location.href='{0}'</script>", Url.Action("CheckIndex", "Resource"));
            //        return Content(script, "text/html");
            //    }
            //}
            ResourceZip aass = (from a in db.ResourceZip where a.ResourceID==rescourceid&&a.PackageFileTitle=="网页端" select a).First() ;
            ViewData["resourcezipid"] = aass.ID;
            ViewData["inboxname"] = aass.InBoxName;

            return View(aa);



        }

        [AllowAnonymous]
        public ActionResult Recommend(int rescourceid,int pagesize = 10, int id = 1)      
        {
            var categoryid= (from a in db.ResourceCategory where a.ResourceID==rescourceid select a.CategoryID).FirstOrDefault();
            PagedList<checkvr> aa = (from a in db.ResourceCategory
                                            where a.CategoryID == categoryid
                                            join b in db.Resource on a.ResourceID equals b.ID
                                            select new checkvr
                         {
                             Location = b.Location,
                             Descrb = b.Descrb,
                             Title = b.Title,
                             subtitle = b.SubTitle,
                             PlayTime = b.PlayTime,
                             PraiseTime = b.PraiseTime,
                             resourceid = b.ID,
                              resourceurl=b.PackageFileName,
                                imageurl=b.ImageshotFileName
                         }).Distinct().OrderBy(b => b.resourceid).ToPagedList(id, pagesize);

            return PartialView(aa);
        }

        //没有加AllowAnonymous 导致js无法执行
     [AllowAnonymous]
        public ActionResult bofangshu(int resourceid) 
        {
            var aa = db.Resource.Single(a => a.ID == resourceid);
            aa.PlayTime = Convert.ToInt32(aa.PlayTime)+1;
            db.Resource.Attach(aa);
            db.Entry(aa).State = EntityState.Modified;
            db.SaveChanges();
            return Json(new { success = true });

        }
         [AllowAnonymous]
        public ActionResult dianzan(int resourceid)
        {
            var aa = db.Resource.Single(a => a.ID == resourceid);
            aa.PraiseTime = Convert.ToInt32(aa.PraiseTime)+1;
            db.Resource.Attach(aa);
            db.Entry(aa).State = EntityState.Modified;
            db.SaveChanges();
            return Json(new {success=true});
            // return Json(new { Success = true, FileName = fileName, SaveName = saveName });
        }

         [AllowAnonymous]
         public ActionResult QRcode(int resourceid, int datazip,string url)
         {
               string inboxname=" ";
               string filepath = Server.MapPath("~/Uploads/" + resourceid + "/"+datazip);
                string[] filenames = Directory.GetFileSystemEntries(filepath);  //获取该文件夹下面的所有文件名
                //  string aaaa;
                foreach (string fname in filenames)    //循环判断每一个文件是否是目录（即文件夹）
                    if (Directory.Exists(fname)) inboxname= fname.Substring(fname.Length - 1, 1);

                string realurl = url+"/Uploads/"+resourceid.ToString()+"/"+datazip.ToString()+"/"+ inboxname +"/"+"index.html";
             QRCodeHandler qr = new QRCodeHandler();
            // string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"/QRCode/";    //文件目录
             string qrString = realurl;                         //二维码字符串
            // string logoFilePath = path + "myLogo.jpg";    
             //Logo路径50*50
             string imagefilepath = Server.MapPath("~/Uploads/"+resourceid +"/"+datazip+ "/myCode.jpg");

             if (!System.IO.File.Exists(filepath))
             {
                 qr.CreateQRCode(qrString, "Byte", 8, 0, "H", imagefilepath, false, null);     
             
             }

          //   string filePath = path + "myCode.jpg";                                        //二维码文件名
           //  qr.CreateQRCode(qrString, "Byte", 8, 0, "H", filepath, false, null);   //生成

             return Json(new { success = true, resourceid = resourceid, datazip = datazip, inboxname = inboxname });
          //   return View();
         
         
         
         }
                  
         [AllowAnonymous]
         public ActionResult QRcodeImage(int resourceid,int datazip,string inboxname)
         {

             ViewData["resourceid"] = resourceid;

             ViewData["datazip"] = datazip;
             ViewData["inboxname"] = inboxname;


             return View();
         }

[Authorize(Roles = "Admin")] 
        public ActionResult VrPass(int rescourceid, int passid) 
        {
            var aa = db.Resource.Single(a => a.ID == rescourceid);
                        if (passid == 1)
                            aa.ResCheck = 1;

                        else aa.ResCheck = 2;
                        db.Resource.Attach(aa);

                        db.Entry(aa).State = EntityState.Modified;
                     db.SaveChanges();
                     return RedirectToAction("CheckIndex");
        
        }



        public ActionResult renderhtml(int rescourceid)
          {

                 string htmlpath = Server.MapPath("~/Uploads/" + rescourceid + "/" + rescourceid + "/" + 2 + "/" + "index.html");
                    string result;
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(htmlpath,System.Text.Encoding.GetEncoding("gb2312")))
               {
                result = sr.ReadToEnd();
                ViewData["htmlresult"] = result;
                sr.Close();        
                sr.Dispose();
            
              }
            return PartialView();
        
        }





        public ActionResult Index(int pagesize = 10, int id = 1, string keyword="" )
        {
            PagedList<RescourcerList> aa;
            if(User.IsInRole("Admin")){

               
                  if(keyword.Trim() !="")
                    aa = (from a in db.Resource
                          where a.Location.Contains(keyword) || a.Title.Contains(keyword) || a.Descrb.Contains(keyword)
                          join b in db.UserProfile on a.UserID equals b.UserId
                          //orderby a.DateTimeStamp descending
                        
                          select new RescourcerList
                          {
                              rescourceid = a.ID,
                              DateTimeStamp = a.DateTimeStamp,
                              Descrb = a.Descrb,
                              LatestModfyDate = a.LatestModfyDate,
                              Location = a.Location,
                              PlayTime = a.PlayTime,
                              PraiseTime = a.PlayTime,
                              Title = a.Title,
                              username = b.UserName,
                              ImageshotFileName = a.ImageshotFileName

                          }).Distinct().OrderBy(a=>a.rescourceid).ToPagedList(id, pagesize);       

        else
            aa = (from a in db.Resource
                                           join b in db.UserProfile on a.UserID equals b.UserId
                                           orderby a.DateTimeStamp descending
                                           select new RescourcerList 
            {
                 rescourceid=a.ID,
                 DateTimeStamp=a.DateTimeStamp,
                 Descrb=a.Descrb,
                 LatestModfyDate=a.LatestModfyDate,
                Location=a.Location,
                PlayTime=a.PlayTime,
                 PraiseTime=a.PlayTime,
                 Title=a.Title,
                  username=b.UserName,
                  ImageshotFileName=a.ImageshotFileName

            }).ToPagedList(id, pagesize);

            return View(aa);
            }
            else{
                if (keyword.Trim() != "")
                {
                    aa = (from a in db.Resource
                          where a.Location.Contains(keyword) || a.Title.Contains(keyword) || a.Descrb.Contains(keyword)
                                                    join b in db.UserProfile on a.UserID equals b.UserId
                                                    where b.UserName == User.Identity.Name                                                    
                                                    select new RescourcerList
                                                    {
                                                        rescourceid = a.ID,
                                                        DateTimeStamp = a.DateTimeStamp,
                                                        Descrb = a.Descrb,
                                                        LatestModfyDate = a.LatestModfyDate,
                                                        Location = a.Location,
                                                        PlayTime = a.PlayTime,
                                                        PraiseTime = a.PlayTime,
                                                        Title = a.Title,
                                                        username = b.UserName,
                                                        ImageshotFileName = a.ImageshotFileName,
                                                        ResCheck = a.ResCheck

                                                    }).Distinct().OrderBy(a=>a.rescourceid).ToPagedList(id, pagesize);
                }
                else {
                     aa = (from a in db.Resource
                                                    join b in db.UserProfile on a.UserID equals b.UserId
                                                    where b.UserName == User.Identity.Name
                                                    orderby a.DateTimeStamp descending
                                                   
                                                    select new RescourcerList
                                                    {
                                                        rescourceid = a.ID,
                                                        DateTimeStamp = a.DateTimeStamp,
                                                        Descrb = a.Descrb,
                                                        LatestModfyDate = a.LatestModfyDate,
                                                        Location = a.Location,
                                                        PlayTime = a.PlayTime,
                                                        PraiseTime = a.PlayTime,
                                                        Title = a.Title,
                                                        username = b.UserName,
                                                        ImageshotFileName = a.ImageshotFileName,
                                                        ResCheck = a.ResCheck

                                                    }).ToPagedList(id, pagesize);              
                
                
                }

                return View(aa);
            }

        }

        public ActionResult ZipUploadFile(int resourceid)
        {


            ViewData["resourceid"] = resourceid;
            return View();

        }



     [AllowAnonymous]
          [HttpPost]

        public ActionResult ZipUploadFile(resourcezip model ,int resourceid )
        {
             
              if(ModelState.IsValid){
                  if ((from a in db.ResourceZip where a.PackageFileTitle == model.resourcezipname.Trim() && a.ResourceID == resourceid select a).Count() > 0)
                  {
                      ModelState.AddModelError("", "名称不能为重复！");
                      ViewData["resourceid"] = resourceid;
                      return View();                                   
                  }
              ResourceZip aa = new ResourceZip();
            aa.ResourceID = resourceid;
            aa.PackageFileTitle = model.resourcezipname;
            db.ResourceZip.Add(aa);
            db.SaveChanges();
            ViewData["resourceid"] = resourceid;
             }
             ViewData["resourceid"] = resourceid;
            return View();
        
        }

          public ActionResult DeleteZipUpload(int id)
          {
           //   var aa = from a  in db.ResourceZip join b in db.Resource on a.ResourceID equals b.ID where a.ID==id select

              ResourceZip aa = db.ResourceZip.Where(a=>a.ID==id).FirstOrDefault();
              int resourceid=aa.ResourceID;

              var OldfileName = (from n in db.ResourceZip where n.ID == id select n.PackageFileName).FirstOrDefault();
              if (OldfileName != null)
              {
                  string oldfilePath = "~/Uploads/" + resourceid + "/" + OldfileName;
                  System.IO.File.Delete(Server.MapPath(oldfilePath));
                  // string oldfileContentPath = "~/Uploads/" + resourceid + "/" + resourceid + "/";
                  string oldfileContentPath = Server.MapPath("~/Uploads/" + resourceid + "/" +id+ "/");
                  //  DeleteDir(oldfileContentPath);
                  DeleteFolder(oldfileContentPath);
              }
              db.ResourceZip.Remove(aa);
              db.SaveChanges();
              return RedirectToAction("ZipUploadFile", new { resourceid = resourceid });

          }



        public ActionResult Ziplist(int resourceid)
        {


            ViewData["resourceid"] = resourceid;
            var aa = from a in db.ResourceZip where a.ResourceID == resourceid select a;

            return PartialView(aa);

        }

        [AllowAnonymous]
        public ActionResult browseList(int resourceid) 
        {
            var aa = from a in db.ResourceZip where a.ResourceID == resourceid select a;
            List<browselistModel> bb = new List<browselistModel>();
            foreach (var a in aa)
            {
                browselistModel cc = new browselistModel();
                cc.resourceid = resourceid;
                cc.zipname = a.PackageFileName;
                cc.resourcezipid = a.ID;
                cc.viewname = db.ResourceZip.Single(x => x.ID == a.ID).PackageFileTitle;
                string filepath = Server.MapPath("~/Uploads/" + resourceid + "/"+a.ID);
                string[] filenames = Directory.GetFileSystemEntries(filepath);  //获取该文件夹下面的所有文件名
                //  string aaaa;
                foreach (string fname in filenames)    //循环判断每一个文件是否是目录（即文件夹）
                    if (Directory.Exists(fname)) cc.inboxname= fname.Substring(fname.Length - 1, 1);
           //     string indexpath = Server.MapPath("~/Uploads/" + rescourceid + "/" + rescourceid + "/" + ViewData["boxname"] + "/" + "index.html");
                bb.Add(cc);
            }

            //if (User.Identity.IsAuthenticated)
            //{
            //    if (!System.IO.File.Exists(indexpath))
            //    {
            //        var script = String.Format("<script>alert('该资源不存在，请上传zip资源包!');location.href='{0}'</script>", Url.Action("CheckIndex", "Resource"));
            //        return Content(script, "text/html");
            //    }
            //}
            //else
            //{
            //    if (!System.IO.File.Exists(indexpath))
            //    {
            //        var script = String.Format("<script>alert('该资源不存在，请上传zip资源包!');location.href='{0}'</script>", Url.Action("nomalIndex", "Resource"));
            //        return Content(script, "text/html");
            //    }
            //}  






            return PartialView(bb);
        
        
        
        }






        [AllowAnonymous]
        public ActionResult browseListIndex(int resourceid)
        {
            var aa = from a in db.ResourceZip where a.ResourceID == resourceid select a;
            List<browselistModel> bb = new List<browselistModel>();
            foreach (var a in aa)
            {
                try {
                browselistModel cc = new browselistModel();
                cc.resourceid = resourceid;
                cc.zipname = a.PackageFileName;
                cc.resourcezipid = a.ID;
                cc.viewname = db.ResourceZip.Single(x => x.ID == a.ID).PackageFileTitle;
                string filepath = Server.MapPath("~/Uploads/" + resourceid + "/" + a.ID);
                string[] filenames = Directory.GetFileSystemEntries(filepath);  //获取该文件夹下面的所有文件名
                //  string aaaa;
                foreach (string fname in filenames)    //循环判断每一个文件是否是目录（即文件夹）
                    if (Directory.Exists(fname)) cc.inboxname = fname.Substring(fname.Length - 1, 1);
                //     string indexpath = Server.MapPath("~/Uploads/" + rescourceid + "/" + rescourceid + "/" + ViewData["boxname"] + "/" + "index.html");
                bb.Add(cc);
                }
                catch {

                }
            }

            //if (User.Identity.IsAuthenticated)
            //{
            //    if (!System.IO.File.Exists(indexpath))
            //    {
            //        var script = String.Format("<script>alert('该资源不存在，请上传zip资源包!');location.href='{0}'</script>", Url.Action("CheckIndex", "Resource"));
            //        return Content(script, "text/html");
            //    }
            //}
            //else
            //{
            //    if (!System.IO.File.Exists(indexpath))
            //    {
            //        var script = String.Format("<script>alert('该资源不存在，请上传zip资源包!');location.href='{0}'</script>", Url.Action("nomalIndex", "Resource"));
            //        return Content(script, "text/html");
            //    }
            //}  






            return PartialView(bb);



        }



        [AllowAnonymous]
        public ActionResult nomalIndex()
        {




        
           

              //var aa = from a in db.Resource
              //                              where a.ResCheck==1
              //       orderby a.DateTimeStamp descending select new RescourcerList
              //       {
              //           rescourceid = a.ID,
              //           PlayTime = a.PlayTime,
              //           PraiseTime = a.PlayTime,
              //           ImageshotFileName = a.ImageshotFileName,
              //                                      Title=a.Title,
              //                                      Descrb=a.Descrb

              //       };


              var newpublic = (from a in db.Resource
                              where a.ResCheck == 1
                              orderby a.DateTimeStamp descending
                              select new RescourcerList
                              {
                                  rescourceid = a.ID,
                                  PlayTime = a.PlayTime,
                                  PraiseTime = a.PlayTime,
                                  ImageshotFileName = a.ImageshotFileName,
                                  Title = a.Title,
                                  Descrb = a.Descrb

                              }).Take(4);
              ViewData["newpublic"] = newpublic;

              var popularity = (from a in db.Resource
                               where a.ResCheck == 1
                               orderby a.PlayTime descending
                               select new RescourcerList
                               {
                                   rescourceid = a.ID,
                                   PlayTime = a.PlayTime,
                                   PraiseTime = a.PlayTime,
                                   ImageshotFileName = a.ImageshotFileName,
                                   Title = a.Title,
                                   Descrb = a.Descrb

                               }).Take(4);
              ViewData["popularity"] = popularity;

              var zan = (from a in db.Resource
                               where a.ResCheck == 1
                               orderby a.PraiseTime descending
                               select new RescourcerList
                               {
                                   rescourceid = a.ID,
                                   PlayTime = a.PlayTime,
                                   PraiseTime = a.PlayTime,
                                   ImageshotFileName = a.ImageshotFileName,
                                   Title = a.Title,
                                   Descrb = a.Descrb

                               }).Take(4);

              ViewData["zan"] = zan;
            return View();




        }
        [AllowAnonymous]
        public ActionResult searchResoult(int pagesize = 10, int id = 1, string keyword = "") 
        {

            if (keyword.Trim() != "")
            {


                PagedList<RescourcerList> bb = (from a in db.Resource

                                                where a.ResCheck == 1 && a.Location.Contains(keyword) || a.Title.Contains(keyword) || a.Descrb.Contains(keyword)
                                                select new RescourcerList
                                                {
                                                    rescourceid = a.ID,
                                                    PlayTime = a.PlayTime,
                                                    PraiseTime = a.PlayTime,
                                                    ImageshotFileName = a.ImageshotFileName,
                                                    Title = a.Title,
                                                    Descrb = a.Descrb,
                                                }).Distinct().OrderBy(a => a.rescourceid).ToPagedList(id, pagesize);
                ViewData["newpublic"] = null;
                ViewData["popularity"] = null;
                ViewData["zan"] = null;
                return View(bb);

            }
            else return RedirectToAction("nomalIndex");
        
        
        }






 [AllowAnonymous]
        public ActionResult Ajaxreach(int categoryid) 
        {






            return Json(new { success = true, categoryid = categoryid});
        
        
        
        }



         [AllowAnonymous]
        public ActionResult ReachIndex(int categoryid = -1, int pagesize = 10, int id = 1) 
        {

           // if (Request.IsAjaxRequest() && categoryid!=-1)
      //      {

                PagedList<RescourcerList> bb = (from a in db.Category
                                                where a.ID == categoryid
                                                join b in db.ResourceCategory on a.ID equals b.CategoryID
                                                join c in db.Resource on b.ResourceID equals c.ID
                                                select new RescourcerList
                                                {
                                                    rescourceid = c.ID,
                                                    PlayTime = c.PlayTime,
                                                    PraiseTime = c.PlayTime,
                                                    ImageshotFileName = c.ImageshotFileName,
                                                    Title = c.Title,
                                                    Descrb = c.Descrb,

                                                }).Distinct().OrderBy(a => a.rescourceid).ToPagedList(id, pagesize);




        //    }
            //else 
            //    return null;

            return View(bb);
        
        
        
        }


        [AllowAnonymous]
        public ActionResult GetCategory() 
        {
           IEnumerable<Category> cate = from a in db.Category where a.ParentID==0 select a;

           var aaaa=cate.Count();


            List<Categoryleft> ccc=new List<Categoryleft>();
   

            foreach (var item in cate) 
            {
                Categoryleft signal = new Categoryleft();
                signal.categoryparent.ID =item.ID;
                signal.categoryparent.Name = item.Name;
                signal.categoryparent.ParentID = 0;
                var child = from c in db.Category where c.ParentID == item.ID select c;
                List<Categorylist> catechild = new List<Categorylist>();
                foreach (var childitem in child) 
                {
                    Categorylist dd = new Categorylist();
                    dd.ID = childitem.ID;
                    dd.Name = childitem.Name;
                    dd.ParentID = item.ID;
                    catechild.Add(dd);              
                
                }
                signal.categorychild = catechild;
                ccc.Add(signal);
            
            }

            return PartialView (ccc as IEnumerable<Categoryleft>);
        
        }



        //
        // GET: /Resource/Details/5

        public ActionResult Details(List<int> selectedIDs)
        {

            return View();
        }

        //
        // GET: /Resource/Create

        public ActionResult ManageCreate()
        {

            return View();
        }


        public ActionResult ManageCreateComfirm( List<int> selectedIDs, string title,  string subtitle, string describe, string location)
        {
                if ((from a in db.Resource where a.Title == title select a).Count() <= 0)
                {
                    var b = from a in db.UserProfile where a.UserName == User.Identity.Name select a;
                    ibl.ManageCreate(title, subtitle, describe, location, b.First().UserId);
                    int resourceid = db.Resource.Single(a => a.Title == title).ID;
                    if (selectedIDs != null)
                    {
                        foreach (var i in selectedIDs)
                        {
                            ResourceCategory aa = new ResourceCategory();
                            aa.ResourceID = resourceid;
                            aa.CategoryID = i;
                            db.ResourceCategory.Add(aa);
                            db.SaveChanges();

                        }
                    }
                     return Json(new { Success = true});
               //     return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);

                //    return RedirectToAction("CreateUploadFile", new { title = title});
                }
                else
                {
                    return Json(new { Success = false, Message = "标题名称已经存在！" }, JsonRequestBehavior.AllowGet);
                 
                }
           
        }

[Authorize(Roles = "Admin")] 
        public ActionResult AddCategory(string Treeid) 
        {
            if (Request.IsAjaxRequest() && Treeid !=null) {
                resourcecategoryid.Add(Convert.ToInt32(Treeid));
                List<Categorylist> resourcecategory = new List<Categorylist>();
                foreach (var item in resourcecategoryid)
                {

                    Categorylist aa = (from a in db.Category
                                       where a.ID == item
                                       select new Categorylist
                                       {
                                           ID = a.ID,
                                           Name = a.Name,
                                           ParentID = a.ParentID
                                       }).FirstOrDefault();
                    resourcecategory.Add(aa);

                }
                return PartialView(resourcecategory as IEnumerable<Categorylist>); 

            } 
            return null;

        
        }
[Authorize(Roles = "Admin")]
        public ActionResult CancelCategory(string Treeid)
        {
            if (Request.IsAjaxRequest() && Treeid!=null)
            {
                resourcecategoryid.Remove(Convert.ToInt32(Treeid));

            }
            return null;
        }

        public ActionResult ResourceCategoryList()
        {
            if(Request.IsAjaxRequest()){
            List<Categorylist> resourcecategory = new List<Categorylist>();
            foreach (var item in resourcecategoryid)
            {

                Categorylist aa = (from a in db.Category
                                   where a.ID == item
                                   select new Categorylist
                                   {
                                       ID = a.ID,
                                       Name = a.Name,
                                       ParentID = a.ParentID
                                   }).FirstOrDefault();
                resourcecategory.Add(aa);

            }
                  return PartialView(resourcecategory);          
            }
            else
                return null;  
            
            
    }

        public ActionResult TijiaoShenHe(int resourceid) 
        {

            if ((from a in db.Resource where a.ID == resourceid select a.ImageshotFileName).FirstOrDefault() == null)
            {
              //  ModelState.AddModelError("", "请上传图片文件");
              //  return View();
              //   CreateUploadFile(string title)              
                var script = String.Format("<script>alert('请上传图片！');location.href='{0}'</script>", Url.Action("CreateUploadFile", "Resource", new{title= db.Resource.Single(a=>a.ID==resourceid).Title}));
                return Content(script, "text/html");
            }
            var aa = db.Resource.Single(a=>a.ID==resourceid);
            aa.ResCheck = 0;
            db.Resource.Attach(aa);
            db.Entry(aa).State = EntityState.Modified;
            db.SaveChanges();

            return RedirectToAction("Index");
        
        
        }
        //
        // POST: /Resource/Create  UploadResourceFile


        public ActionResult CreateUploadFile(string title)
        {
            var resourceid = (from a in db.Resource where a.Title == title select a).First().ID;

            ViewData["resourceid"] = resourceid;
            return View();
        }



        [HttpPost]
        public ActionResult CreateUploadFile(string resourceid, string checkbtn )
        {
            ViewData["resourceid"] = resourceid;
           if(ModelState.IsValid)
            {
                  int rescourceidint=Convert.ToInt32(resourceid);
                  if ((from a in db.Resource where a.ID == rescourceidint select a.ImageshotFileName).FirstOrDefault() == null)
                {
                    ModelState.AddModelError("", "请上传图片文件");
                    return View();
                }
                else
                {
                    Resource tt = (from a in db.Resource where a.ID == rescourceidint select a).First();
                    if (checkbtn ==null) {
                        tt.ResCheck = 3;
                        db.Resource.Attach(tt);
                        db.Entry(tt).State = EntityState.Modified;
                        db.SaveChanges();
                        //return View();
                        return RedirectToAction("Index");    
                    }
                    if (Convert.ToInt32(checkbtn) == 0) {
                        tt.ResCheck =2;
                    }
                    else if (Convert.ToInt32(checkbtn) == 1) tt.ResCheck = 1;

                        db.Resource.Attach(tt);
                        db.Entry(tt).State = EntityState.Modified;
                        db.SaveChanges();
                        //return View();
                        return RedirectToAction("Index");
                }
            }
            else
            {
                return View();
            }
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult addimage(HttpPostedFileBase fileData, int resourceid,int state)
        {
            if (fileData != null)
            {
                //删除原有文件
               // int questionsetid1 = Convert.ToInt32(questionsetid);
                var OldfileName = (from n in db.Resource where n.ID == resourceid select n.ImageshotFileName).FirstOrDefault();
                if (OldfileName != null)
                {
                    string oldfilePath = "~/Uploads/" + resourceid + "/" +OldfileName;
                    System.IO.File.Delete(Server.MapPath(oldfilePath));
                }
                try
                {
                    //      int questionsetid1 = Convert.ToInt32(questionsetid);
                    string filePath = Server.MapPath("~/Uploads/" + resourceid + "/");
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    string fileName = Path.GetFileName(fileData.FileName);// 原始文件名称
                    string fileExtension = Path.GetExtension(fileName); // 文件扩展名
                    string saveName = resourceid.ToString() + fileExtension;// 保存文件名称
                    //  if()
                    var path = Path.Combine(filePath, saveName);
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(Server.MapPath(path));
                    }
                    fileData.SaveAs(path);
                    Resource tt = db.Resource.Where(a => a.ID == resourceid).First();
                    tt.ImageshotFileName = saveName;
                    db.Resource.Attach(tt);
                    db.Entry(tt).State = EntityState.Modified;
                    db.SaveChanges();
                    return Json(new { Success = true, FileName = fileName, SaveName = saveName });
                }
                catch (Exception ex)
                {
                    return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
                }
            }

            else{

                return Json(new { Success = false, Message = "请选择要上传的文件！" }, JsonRequestBehavior.AllowGet);
            }
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult uploadzip(HttpPostedFileBase fileData, int resourceid, int resourcezipid, int state)
        {
            if (fileData != null)
            {
                //删除原有文件
                // int questionsetid1 = Convert.ToInt32(questionsetid);
                var OldfileName = (from n in db.ResourceZip where n.ID == resourcezipid select n.PackageFileName).FirstOrDefault();
                if (OldfileName != null)
                {
                    string oldfilePath = "~/Uploads/" + resourceid + "/" + OldfileName;
                    System.IO.File.Delete(Server.MapPath(oldfilePath));
                   // string oldfileContentPath = "~/Uploads/" + resourceid + "/" + resourceid + "/";
                    string oldfileContentPath = Server.MapPath("~/Uploads/" + resourceid + "/" + resourcezipid + "/");
                  //  DeleteDir(oldfileContentPath);
                    DeleteFolder(oldfileContentPath);
                }

                try
                {
                    //      int questionsetid1 = Convert.ToInt32(questionsetid);
                    string filePath = Server.MapPath("~/Uploads/" + resourceid + "/");
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    string fileName = Path.GetFileName(fileData.FileName);// 原始文件名称
                    string fileExtension = Path.GetExtension(fileName); // 文件扩展名
                    string saveName = resourcezipid.ToString() + fileExtension;// 保存文件名称
                    //  if()
                    var path = Path.Combine(filePath, saveName);
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(Server.MapPath(path));
                    }
                    fileData.SaveAs(path);
                    ResourceZip tt = db.ResourceZip.Where(a => a.ID ==resourcezipid).First();
                    tt.PackageFileName = saveName;
                    db.ResourceZip.Attach(tt);
                    db.Entry(tt).State = EntityState.Modified;
                    db.SaveChanges();
                    string unzippath = Server.MapPath("~/Uploads/"+resourceid+"/"+resourcezipid +"/");
                //    try {
                        UnZip(path, unzippath, true);

                        string filepath = Server.MapPath("~/Uploads/" + resourceid + "/" + resourcezipid);
                        string[] filenames = Directory.GetFileSystemEntries(filepath);  //获取该文件夹下面的所有文件名
                          string aaaa="";
                        foreach (string fname in filenames)    //循环判断每一个文件是否是目录（即文件夹）
                        if (Directory.Exists(fname)) aaaa = fname.Substring(fname.Length - 1, 1);
                        ResourceZip tem = db.ResourceZip.Where(a => a.ID == resourcezipid).First();
                        tem.InBoxName=aaaa;
                        db.ResourceZip.Attach(tem);
                        db.Entry(tem).State = EntityState.Modified;
                        db.SaveChanges();

             //       }
                //        catch
                //        {
                //            return Json(new { Success = 1 });
                //         //   var script = String.Format("<script>alert('该资源包解析错误，请重新上传该zip包！');location.href='{0}'</script>", Url.Action("Ziplist", "Resource", new { resourceid=resourceid}));
                //        //    return Content(script, "text/html");
                //        }                  
                //    string inboxname="";
                //    string filepath = Server.MapPath("~/Uploads/" + resourceid + "/" + resourcezipid);
                //    string[] filenames = Directory.GetFileSystemEntries(filepath);  //获取该文件夹下面的所有文件名
                //    //  string aaaa;
                //    foreach (string fname in filenames)    //循环判断每一个文件是否是目录（即文件夹）
                //        if (Directory.Exists(fname)) inboxname = fname.Substring(fname.Length - 1, 1);

                //    string indexpath = Server.MapPath("~/Uploads/"+resourceid+"/"+resourcezipid+"/"+inboxname + "/"+"index.html");

                //    if (!System.IO.File.Exists(indexpath))
                //    {

                //        return Json(new { Success =2 });

                // //       var script = String.Format("<script>alert('该资源不存在，请上传zip资源包!');location.href='{0}'</script>", Url.Action("ZipUploadFile", "Resource", new { resourceid = resourceid}));
                ////        return Content(script, "text/html");
                //    }
                   
                    return Json(new { Success = true,Resourceid = resourceid});
                  //  return Json(new { success = true, resourceid = resourceid, datazip = datazip, inboxname = inboxname });
                }
                catch (Exception ex)
                {
                    return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {

                return Json(new { Success = false, Message = "请选择要上传的文件！" }, JsonRequestBehavior.AllowGet);
            }
        }

        //public ActionResult CreateZipName(string resourcezipname) 
        //{
        //    if (ModelState.IsValid) 
        //    { 
            
            
            
            
        //    }
        
        
        
        
        //}
        //
        // GET: /Resource/Edit/5

        public ActionResult EditResourceFirstPart(int resourceid)
        {
            var aa = (from a in db.Resource where a.ID == resourceid select a).FirstOrDefault();
            ViewData["resourceid"] = resourceid;
            EditResourceFirstPart bb = new EditResourceFirstPart();
            bb.title = aa.Title;
            bb.subtitle = aa.SubTitle;
            bb.describe = aa.Descrb;
            bb.location = aa.Location;
            bb.editcategorylist = (from a in db.ResourceCategory where a.ResourceID==resourceid
                                  join b in db.Category  on a.CategoryID equals b.ID
                                  select new editcategory
                                      {
                                          resource_category_id = a.ID,
                                          categoryname = b.Name,

                                      }).ToList<editcategory>();

            return View(bb);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Edit_deleteCategory(int resource_category_id, int resourceid) 
        {



            ResourceCategory aa = db.ResourceCategory.Single(a => a.ID == resource_category_id);
            db.ResourceCategory.Remove(aa);
            db.SaveChanges();
           var editcategorylist = (from a in db.ResourceCategory
                                   where a.ResourceID == resourceid
                                   join b in db.Category on a.CategoryID equals b.ID
                                   select new editcategory
                                   {
                                       resource_category_id = a.ID,
                                       categoryname = b.Name,

                                   }).ToList<editcategory>();
               return Json(new { Success = true, categorydata = editcategorylist },JsonRequestBehavior.AllowGet);
        
        }



        public ActionResult Edit_AddCategory(int category_id, int resourceid) 
        {
            if ((from a in db.ResourceCategory where a.CategoryID == category_id && a.ResourceID == resourceid select a).Count() > 0) 
            {
                return null;        
            }
            ResourceCategory aa = new ResourceCategory();
            aa.CategoryID = category_id;
            aa.ResourceID = resourceid;
            db.ResourceCategory.Add(aa);
            db.SaveChanges();
           var editcategorylist = (from a in db.ResourceCategory
                                   where a.ResourceID == resourceid
                                   join b in db.Category on a.CategoryID equals b.ID
                                   select new editcategory
                                   {
                                       resource_category_id = a.ID,
                                       categoryname = b.Name,

                                   }).ToList<editcategory>();
               return Json(new { Success = true, categorydata = editcategorylist },JsonRequestBehavior.AllowGet);
        
        }


        //
        // POST: /Resource/Edit/5

        [HttpPost]
        public ActionResult EditResourceFirstPart(int resourceid, CreateResource Model)
        {
            if (ModelState.IsValid) 
            {

                Resource EditResource = (from a in db.Resource where a.ID == resourceid select a).FirstOrDefault();
                EditResource.Title = Model.title;
                EditResource.SubTitle = Model.subtitle;
                EditResource.Location = Model.location;
                EditResource.Descrb = Model.describe;
                db.Resource.Attach(EditResource);
                db.Entry(EditResource).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("EditResourceSecondPart", new { resourceid=resourceid});
            }
            else
            {
                return View();
            }
        }

        public ActionResult EditResourceSecondPart(int resourceid)
        {
            var aa = (from a in db.Resource where a.ID == resourceid select a).FirstOrDefault();
            ViewData["resourceid"] = resourceid;
            UploadResourceFile bb = new UploadResourceFile();
            bb.checkornot = aa.ResCheck;
            return View(bb);

        }

        [HttpPost]
        public ActionResult EditResourceSecondPart(int resourceid, UploadResourceFile Model)
        {
            if (ModelState.IsValid)
            {
                if (User.IsInRole("Admin"))
                {
                    Resource EditResource = (from a in db.Resource where a.ID == resourceid select a).FirstOrDefault();
                    EditResource.ResCheck = Model.checkornot;
                    EditResource.LatestModfyDate = DateTime.Now;
                    db.Resource.Attach(EditResource);
                    db.Entry(EditResource).State = EntityState.Modified;
                    db.SaveChanges();
                }
                else {

                    Resource EditResource = (from a in db.Resource where a.ID == resourceid select a).FirstOrDefault();
                    EditResource.LatestModfyDate = DateTime.Now;
                    db.Resource.Attach(EditResource);
                    db.Entry(EditResource).State = EntityState.Modified;
                    db.SaveChanges();             
                
                }
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }

        public ActionResult DeleteComfirm(int resourceid)
        {
            Resource aa = db.Resource.Where(a => a.ID == resourceid).FirstOrDefault();

            return View(aa);
        }

        //
        // GET: /Resource/Delete/5

        public ActionResult Delete(int resourceid)
        {
           var ar = from a in db.ResourceCategory where a.ResourceID == resourceid select a;
           foreach (var i in ar) {
               db.ResourceCategory.Remove(i);                
           }
           db.SaveChanges();
           var b = from a in db.ResourceZip where a.ResourceID == resourceid select a;
           foreach (var i in b)
           {
               db.ResourceZip.Remove(i);
           }
           db.SaveChanges();

            Resource aa = db.Resource.Where(a => a.ID == resourceid).FirstOrDefault();
            db.Resource.Remove(aa);

            db.SaveChanges();
            string filePath = "~/Uploads/" + resourceid.ToString() + "/";
            string deletepath = Server.MapPath(filePath);
            if (Directory.Exists(deletepath))
            {
                System.IO.Directory.Delete(@deletepath, true);
            }
            return RedirectToAction("Index");
        }

        //
        // POST: /Resource/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
